﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Options.IBClient.Component
{
    public class ClientYahoo
    {

        // Field 
        public string _symbol;

        // Constructor that takes one argument. 
        public ClientYahoo(string symbol)
        {
            _symbol = symbol;
        }

        // Method 
        public String getSMA()
        {
            try
            {
                String str = null;
                // Use Yahoo finance service to download stock data from Yahoo
                string url = @"http://download.finance.yahoo.com/d/quotes.csv?s=" + _symbol + "&f=sl1m3m4";
                // Creates an HttpWebRequest with the specified URL. 
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                // Sends the HttpWebRequest and waits for the response.			
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                // Gets the stream associated with the response.
                Stream receiveStream = myHttpWebResponse.GetResponseStream();
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                // Pipes the stream to a higher level stream reader with the required encoding format. 
                StreamReader readStream = new StreamReader(receiveStream, encode);
                Char[] read = new Char[256];
                // Reads 256 characters at a time.     
                int count = readStream.Read(read, 0, 256);
                while (count > 0)
                {
                    // Dumps the 256 characters on a string and displays the string to the console.
                    str = new String(read, 0, count);
                    count = readStream.Read(read, 0, 256);
                }
                // Releases the resources of the response.
                myHttpWebResponse.Close();
                // Releases the resources of the Stream.
                readStream.Close();
                return str;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}
